package com.luckymore.ydd.app.funcs.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.base.cache.ACacheUtil;
import com.base.control.ContextControl;
import com.base.control.MActivitySupport;
import com.base.control.TaskWithExceptionHandler;
import com.base.control.TextParamCheck;
import com.base.control.VisibleControl;
import com.base.model.Bean2Json;
import com.base.util.ConstantResource;
import com.base.util.Helper;
import com.base.util.MLog;
import com.base.util.StringUtil;
import com.base.util.Utils;
import com.luckymore.ydd.app.R;
import com.luckymore.ydd.app.cache.CacheUtil;
import com.luckymore.ydd.app.funcs.mainfuncs.MainFuncsActivity;
import com.luckymore.ydd.app.model.MAppUser;
import com.luckymore.ydd.app.net.ApiClientFactory;
import com.luckymore.ydd.app.net.DefaultRequestCallback;
import com.luckymore.ydd.app.net.MUserCallback;
import com.luckymore.ydd.app.util.AppConfig;
import com.luckymore.ydd.app.util.MErrors;
import com.luckymore.ydd.app.util.MHelper;
import com.luckymore.ydd.app.util.MobileKeySet;
import com.luckymore.ydd.app.util.ShareUtils;
import com.luckymore.ydd.app.util.UITextUtil;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMSsoHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by yjh on 15-3-10.
 */
public class LoginActivity extends MActivitySupport {
    private Button loginBtn;
    private Button registerBtn;
    private AutoCompleteTextView usernameEditor;
    private EditText passwordEditor;
    private ImageView qqIv;
    private ImageView wxIv;
    private ImageView wbIv;
    private TextView forgetPasswd;
    private LinearLayout mainContent;
    private LinearLayout loginOtherLayout;
    private ImageView loginLogo;

    private boolean isLoginVerifyError = false;

    private MAppUser.MUser mUser = new MAppUser.MUser();
    private boolean isEncrypt = false;
    private String encryptPassword;
    private MAppUser.MUserList users;
    private int type = 0;
    private String oldUSERID = "";

    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");

    @Override
    protected void create(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);

        mainContent = mFindViewById(R.id.login_div);
        loginOtherLayout = mFindViewById(R.id.login_other);
        loginLogo = mFindViewById(R.id.login_logo);

        users = (MAppUser.MUserList)getStartData();
        type = getStartType();

        //背景外的控件淡入
        VisibleControl.fadeIn(mainContent, this);
        VisibleControl.fadeIn(loginOtherLayout, this);
        VisibleControl.fadeIn(loginLogo, this);

        loginBtn = mFindViewById(R.id.login_signin_button);
        registerBtn = mFindViewById(R.id.login_register_button);
        usernameEditor = mFindViewById(R.id.login_username_edit);
        passwordEditor = mFindViewById(R.id.login_password_edit);

        qqIv = mFindViewById(R.id.login_qq);
        wxIv = mFindViewById(R.id.login_wx);
        wbIv = mFindViewById(R.id.login_wb);

        forgetPasswd = mFindViewById(R.id.login_forget_pwd);

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });

        //绑定注册按钮
        ContextControl.bindClickStartAcitivity(this, RegisterActivity.class, registerBtn, false);

        //忘记密码
        Bundle data = new Bundle();
        data.putInt(MobileKeySet.REGISTER_START_METHOD, 1); //表示忘记页面页面
        ContextControl.bindClickStartAcitivity(this, RegisterActivity.class, forgetPasswd, false, data);

        //一旦手动修改，表明不是明码
        usernameEditor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                isEncrypt = false;
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        if(type != 1) {
            Intent intent = getIntent();
            isLoginVerifyError = intent.getIntExtra(ConstantResource.LOGIN_VERIFY_ERROR_KEY, -1) == 1;
            if(isLoginVerifyError) {
                AppConfig.changeAccount(this); //重置化全局参数
            }

            //读取缓存用户信息
            mUser = ACacheUtil.getData(this, CacheUtil.USER_INFO_CACHE_KEY);
            if(mUser != null) {
                oldUSERID = mUser.getId();
                encryptPassword = mUser.getPasswordEncrypt();
                if(!StringUtil.isEmpty(mUser.getPhone())) {
                    usernameEditor.setText(mUser.getPhone());
                } else {
                    usernameEditor.setText(mUser.getAccount());
                }
                if(!StringUtil.isEmpty(mUser.getPassword())) {
                    passwordEditor.setText(mUser.getPassword());
                } else {
                    if(!StringUtil.isEmpty(encryptPassword)) {
                        isEncrypt = true;
                        passwordEditor.setText(encryptPassword.substring(0, 9));
                    }
                }
            }

            //非登录验证失败跳转至此时，有用户缓存直接进首页
            if(!isLoginVerifyError) {
                this.clearActivity(this.getClass()); //清空其他所有activity
            }
        } else {
            usernameEditor.setDropDownBackgroundResource(R.color.alpha_white_deep);
            usernameEditor.setAdapter(new ArrayAdapter<>(getMActivity(), R.layout.item_login_accounts, getUserAccount()));
            usernameEditor.postDelayed(new Runnable() {
                @Override
                public void run() {
                    usernameEditor.showDropDown();
                }
            }, 1000);
            usernameEditor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    MLog.d(users.getUser());
                    encryptPassword = users.getUser().get(i).getPasswordEncrypt();
                    MLog.d("xxxxxxx" + encryptPassword);
                    if(!StringUtil.isEmpty(encryptPassword)) {
                        if (encryptPassword.length() >= 9)
                            passwordEditor.setText(encryptPassword.substring(0, 9));
                        else
                            passwordEditor.setText(encryptPassword);
                    } else {
                        passwordEditor.setText("");
                    }
                    isEncrypt = true;
                }
            });
        }


        ShareUtils.share(getMActivity());
        bindQQ();
        bindWX();

    }

    private void bindWX() {
        wxIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mController.doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, new SocializeListeners.UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA platform) {
                    }
                    @Override
                    public void onError(SocializeException e, SHARE_MEDIA platform) {
                    }
                    @Override
                    public void onComplete(Bundle value, SHARE_MEDIA platform) {
                        //获取相关授权信息
                        mController.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, new SocializeListeners.UMDataListener() {
                            @Override
                            public void onStart() {
                            }
                            @Override
                            public void onComplete(int status, final Map<String, Object> info) {
                                if(status == 200 && info != null){
                                    //获取用户登录信息

                                    String openid = StringUtil.emptyIfBlank((String)(info.get("openid")));

                                    ApiClientFactory.loginByWx(getMActivity(), new MUserCallback() {
                                        @Override
                                        public void onGetUserData(MAppUser.MUser mUser) {
                                            super.onGetUserData(mUser);
                                            LoginActivity.this.mUser = mUser;
                                            changeDifferentAccount();
                                            if(StringUtil.isEmpty(mUser.getNickname()))
                                                mUser.setNickname(StringUtil.emptyIfBlank((String)(info.get("nickname"))));
                                            if(StringUtil.isEmpty(mUser.getHeadImg()))
                                                mUser.setHeadImg(StringUtil.emptyIfBlank((String)(info.get("headimgurl"))));

                                            CacheUtil.updateUserInfo(getMActivity(), mUser, null, 1);
                                            //清楚文件头像缓存
                                            MHelper.clearUserHeadImgFile();

                                            ApiClientFactory.updateUserInfo(getMActivity(), new DefaultRequestCallback(), null,
                                                    mUser.getNickname(), null, mUser.getSex(), mUser.getEmail());

                                            ContextControl.startContext(getMActivity(), MainFuncsActivity.class, true);
                                        }
                                    }, null, openid);
                                }
                            }
                        });
                    }
                    @Override
                    public void onCancel(SHARE_MEDIA platform) {
                    }
                } );
            }
        });
    }

    private void bindQQ() {
        qqIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mController.doOauthVerify(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA platform) {
                    }
                    @Override
                    public void onError(SocializeException e, SHARE_MEDIA platform) {
                    }
                    @Override
                    public void onComplete(Bundle value, SHARE_MEDIA platform) {
                        //获取相关授权信息
                        mController.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMDataListener() {
                            @Override
                            public void onStart() {
                            }
                            @Override
                            public void onComplete(int status, final Map<String, Object> info) {
                                if(status == 200 && info != null){
                                    StringBuilder sb = new StringBuilder();
                                    Set<String> keys = info.keySet();
                                    for(String key : keys) {
                                        sb.append(key+"="+info.get(key).toString()+"\r\n");
                                    }
                                    //获取用户登录信息
                                    String openid = UITextUtil.qqAccountGet(StringUtil.emptyIfBlank((String)(info.get("profile_image_url"))));
                                    MLog.d(info);
                                    ApiClientFactory.loginByQQ(getMActivity(), new MUserCallback() {
                                        @Override
                                        public void onGetUserData(MAppUser.MUser mUser) {
                                            super.onGetUserData(mUser);
                                            LoginActivity.this.mUser = mUser;
                                            changeDifferentAccount();
                                            if(StringUtil.isEmpty(mUser.getNickname()))
                                                mUser.setNickname(StringUtil.emptyIfBlank((String)(info.get("screen_name"))));
                                            if(StringUtil.isEmpty(mUser.getHeadImg()))
                                                mUser.setHeadImg(StringUtil.emptyIfBlank((String)(info.get("profile_image_url"))));
                                            String sexTemp = StringUtil.emptyIfBlank((String)(info.get("gender")));
                                            if(sexTemp.equals("女"))
                                                mUser.setSex(1);
                                            CacheUtil.updateUserInfo(getMActivity(), mUser, null, 1);
                                            //清楚文件头像缓存
                                            MHelper.clearUserHeadImgFile();

                                            ApiClientFactory.updateUserInfo(getMActivity(), new DefaultRequestCallback(), null,
                                                    mUser.getNickname(), null, mUser.getSex(), mUser.getEmail());

                                            ContextControl.startContext(getMActivity(), MainFuncsActivity.class, true);
                                        }
                                    }, null, openid);
                                }
                            }
                        });
                    }
                    @Override
                    public void onCancel(SHARE_MEDIA platform) {
                    }
                } );
            }
        });
    }

    //重写系统back键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Helper.exit(this);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private List<String> getUserAccount() {
        List<String> keys = new ArrayList<>();
        for(MAppUser.MUser user : users.getUser()) {
            if(!StringUtil.isEmpty(user.getPhone())) {
                keys.add(user.getPhone());
            } else {
                keys.add(user.getAccount());
            }
        }
        return keys;
    }

    private boolean login() {
        //检查参数，异常时用Toast显示错误信息
        return new TaskWithExceptionHandler() {
            @Override
            public void onCheck() throws Exception {
                TextParamCheck
                        .check(usernameEditor.getText().toString(), MErrors.ACCOUNT_EMPTY, MErrors.ACCOUNT_FORMAT_ERROR, TextParamCheck.LOGIN_ACCOUNT_CHECKER);

                TextParamCheck
                        .check(passwordEditor.getText().toString(), MErrors.PASSWD_EMPTY, MErrors.EMPTY, TextParamCheck.EMPTY_CHECKER);

                String password;
                if(isEncrypt) {
                    password = encryptPassword;
                } else {
                    password = AppConfig.PASSWORD = passwordEditor.getText().toString();
                }

                if (Utils.isNetworkConnected(getMActivity())) {
                    ApiClientFactory.login(LoginActivity.this, LoginActivity.this, "loginSuccess", usernameEditor.getText().toString(), password,
                            isEncrypt);
                } else {
                    if(ACacheUtil.getData(getMActivity(), CacheUtil.USER_INFO_CACHE_KEY) != null) {
                        ContextControl.startContext(getMActivity(), MainFuncsActivity.class, true);
                    } else {
                        Helper.toast(getMActivity(), ConstantResource.NET_ERROR);
                    }
                }
            }
        }.work(this);
    }

    public void loginSuccess(Bean2Json data) {
        mUser = (MAppUser.MUser)data;
        if(mUser != null) {
            changeDifferentAccount();
            AppConfig.checkIsNewUser(mUser);
            mUser.setPasswordEncrypt(encryptPassword);
            //更新缓存
            CacheUtil.updateUserInfo(this, mUser, AppConfig.PASSWORD);
            Helper.toast(this, "登录成功");
            if(!isLoginVerifyError)
                ContextControl.startContext(this, MainFuncsActivity.class, true);
            else //登录验证失败跳转至此时，登录成功登录activity退出栈
                this.finish();
        }
    }

    public void changeDifferentAccount() {
        if(!oldUSERID.equals(mUser.getId())) {
            AppConfig.isDifferentAccount = true;
            AppConfig.setCourseList(null, this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode) ;
        if(ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
